package diycode

import (
	"fmt"
	"math"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

type Number interface {
	~int | ~int64
}

// N进制转十进制
func Base2to10[T Number](num T, base T) T {
	var res T
	n := int64(num)
	b := int64(base)

	str := fmt.Sprintf("%v", n)
	arr := strings.Split(str, "")

	for i, code := range arr {
		parseNum, _ := strconv.ParseInt(code, 0, 0)
		adder := parseNum * int64(math.Pow(float64(b), float64(len(arr)-i-1)))
		res += T(adder)
	}
	return res
}

// 十进制转N进制
func N10toBase[T Number](num T, base T) []T {
	res := []T{}

	for {
		res = append(res, T(num%base))
		num = (num - (num % base)) / base
		if num < base {
			res = append(res, T(num%base))
			break
		}
	}

	for i := len(res) - 1; i >= 0; i-- {
		if res[i] == 0 {
			res = res[:len(res)-1]
			continue
		} else {
			break
		}
	}

	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}

	return res
}

func strLen(s string) int {
	return len([]rune(s))
}

// 打乱数组
func Shuffle[T any](arr []T) []T {
	rand.Seed(time.Now().UnixNano())
	rand.Shuffle(len(arr), func(i, j int) {
		arr[i], arr[j] = arr[j], arr[i]
	})
	return arr
}

// 打乱字符串
func ShuffleStr(str string) string {
	arr := strings.Split(str, "")
	return strings.Join(Shuffle(arr), "")
}
